package com.tool4j.service;

import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Properties;

@Service
@Slf4j
public class MailService {

    @Value("${spring.mail.username}")
    private String username;
    @Value("${spring.mail.password}")
    private String password;

    private static final String sign = "\n\n\n----------------------------\n【Tool4J】\n" +
            "www.tool4j.com\n" +
            "Chat-AI工具站\n" +
            "E-mail：tool4j@163.com\n";

    /**
     * 发送信息邮件
     *
     * @param to      收件人
     * @param title   标题
     * @param content 内容
     */
    public void sendMail(String to, String title, String content) {
        try {
            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", "smtp.163.com");
            props.put("mail.smtp.port", "587");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            Session session = Session.getInstance(props, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(to));
            message.setSubject(title);
            // 添加签名
            Multipart multipart = new MimeMultipart();
            BodyPart bodyPart = new MimeBodyPart();
            bodyPart.setText(content + sign);
            multipart.addBodyPart(bodyPart);
            message.setContent(multipart);
            //发送
            Transport.send(message);
            log.info("\n>>>>>>>>>>>>>> 邮件发送成功：email = {}, title = {}, content = {}", to, title, content);
        } catch (Exception e) {
            log.error("\n>>>>>>>>>>>>>> 邮件发送失败：email = {}, content = {}", to, title, content, e);
        }
    }
}
